package cn.git.shiro.relam;

import cn.git.shiro.constant.ShiroJWTConstant;
import cn.git.shiro.entity.User;
import cn.git.shiro.token.JwtToken;
import cn.git.shiro.util.JWTUtil;
import cn.git.shiro.util.RedisUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description: 自定义shiro权限认证realm
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-03-27
 */
@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 判断是否支持此token，必须重写此方法，不然Shiro会报错
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 权限信息
        return null;
    }

    /**
     * 认证
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取jwtToken
        String jwtToken = StrUtil.toString(token.getPrincipal());
        // 校验jwtToken合法性
        if (!jwtUtil.verifyJWTToken(jwtToken) || jwtUtil.ifTokenExpire(jwtToken)) {
            throw new RuntimeException("当前token非法!");
        }
        // 获取用户信息
        if (!redisUtil.hHasKey(ShiroJWTConstant.JWT_TOKEN_FLAG, jwtToken)) {
            throw new RuntimeException("缓存获取登录用户信息失败!");
        }
        String userJSONStr = (String) redisUtil.hget(ShiroJWTConstant.JWT_TOKEN_FLAG, jwtToken);
        User loginUser = JSONObject.parseObject(userJSONStr, User.class);

        // 封装认证信息，在DefaultWebSecurityManager配置中没有指定Matcher密码验证器，所以这里不验证密码，封装SimpleAuthenticationInfo直接通过
        return new SimpleAuthenticationInfo(
                loginUser,
                jwtToken,
                this.getName());
    }
}
